package com.bjtu.literatureclient.controller.journal;

import com.bjtu.literatureclient.api.vo.request.JournalCnEditRequest;
import com.bjtu.literatureclient.api.vo.request.PageListRequest;
import com.bjtu.literatureclient.api.vo.response.JournalCnResponse;
import com.bjtu.literatureclient.api.vo.response.JournalEnResponse;
import com.bjtu.literatureclient.base.result.Result;
import com.bjtu.literatureclient.controller.user.UserController;
import com.bjtu.literatureclient.domain.Author;
import com.bjtu.literatureclient.domain.authorindex.AuthorIndex;
import com.bjtu.literatureclient.domain.journal.JournalEnglish;
import com.bjtu.literatureclient.domain.journal.JournalPaperChinese;
import com.bjtu.literatureclient.domain.journal.JournalPaperEnglish;
import com.bjtu.literatureclient.domain.user.User;
import com.bjtu.literatureclient.service.authorindex.AuthorIndexService;
import com.bjtu.literatureclient.service.journal.IJournalService;
import com.bjtu.literatureclient.service.user.IUserService;
import com.bjtu.literatureclient.service.user.UserIndexService;
import com.bjtu.literatureclient.util.UserUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/journal")
public class JournalController {

	private final static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private IUserService userService;
	@Autowired
	UserIndexService userIndexService;
	@Autowired
	private IJournalService journalService;
	@Autowired
	private AuthorIndexService authorIndexService;


	@RequestMapping(value = "/journal-cn-list", method = RequestMethod.POST)
	@ApiOperation("中文期刊List")
	public PageInfo<JournalCnResponse> journalList(@RequestBody @Validated PageListRequest request){
		PageHelper.startPage(request.getPageNo(), request.getPageSize());
		User curUser = UserUtil.getCurUser();
		List<JournalCnResponse> journalCnResponses =  journalService.getJournalCnResponseList(curUser);
		PageInfo<JournalCnResponse> response = new PageInfo<>(journalCnResponses);
		return response;
	}

	@RequestMapping(value = "/journal-en-list", method = RequestMethod.POST)
	@ApiOperation("西文期刊List")
	public PageInfo<JournalEnResponse> journaEnlList(@RequestBody @Validated PageListRequest request){
		PageHelper.startPage(request.getPageNo(), request.getPageSize());
		User curUser = UserUtil.getCurUser();
		List<JournalEnResponse> journalEnResponses =  journalService.getJournalEnResponseList(curUser);
		PageInfo<JournalEnResponse> response = new PageInfo<>(journalEnResponses);
		return response;
	}

	@RequestMapping(value = "/edit-journal-cn", method = RequestMethod.POST)
	@ApiOperation("中文期刊修改")
	public Result<Boolean> journalEdit(@RequestBody JournalCnEditRequest request){
		Boolean result =  journalService.editJournalCn(request);
		return Result.success(result);
	}

	@RequestMapping(value = "/edit-journal-en", method = RequestMethod.POST)
	@ApiOperation("西文期刊修改")
	public Result<Boolean> journalEdit(@RequestBody JournalEnglish request){
		Boolean result =  journalService.editJournalEn(request);
		return Result.success(result);
	}



	@RequestMapping(value = "/queryJournalPaper", method = RequestMethod.POST)
	public String queryJournalPaperChinese( HttpServletRequest request) {
		String type=request.getParameter("type");
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user=(User) session.getAttribute("userInfo");
		List<?> journal = journalService.queryJournalPaper(type,user.getUserNo());
		Gson gson = new Gson();
		return gson.toJson(journal);

	}
	@RequestMapping(value = "/queryJournalPaperByIndexNo", method = RequestMethod.POST)
	public String queryJournalPaperByIndexNo(@RequestBody Map<String, Object> params) {
		String type= (String) params.get("type");
		String indexNo= (String) params.get("indexNo");
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user=(User) session.getAttribute("userInfo");
		JournalPaperEnglish journalPaperEnglish =new JournalPaperEnglish();
		JournalPaperChinese journalPaperChinese =new JournalPaperChinese();
		Gson gson = new Gson();
		if(type.equals("1")){
			journalPaperEnglish= (JournalPaperEnglish) journalService.queryJournalPaperByIndexNo(type,user.getUserNo(),indexNo);
			return gson.toJson(journalPaperEnglish);
		}else{
			journalPaperChinese = (JournalPaperChinese) journalService.queryJournalPaperByIndexNo(type,user.getUserNo(),indexNo);
			return gson.toJson(journalPaperChinese);
		}



	}
	@RequestMapping(value = "/queryJournal", method = RequestMethod.POST)
	public String queryJournalChinese( HttpServletRequest request) {
		String type=request.getParameter("type");
		List<?> journal = journalService.queryJournalChinese(type);
		Gson gson = new Gson();
		return gson.toJson(journal);
	}

	@RequestMapping(value = "/addJournalPaper", method = RequestMethod.POST)
	public String addJournalPaper(@RequestBody Map<String, Object> params) {
		Integer type = (Integer) params.get("type");
		List<AuthorIndex> authors = new ArrayList<AuthorIndex>();
		String authorInfo=(String)params.get("tableInfo");
		String[] author=authorInfo.split(";");
		String str1 ="";
		for (int i = 0; i < author.length; i++) {
			AuthorIndex a = new AuthorIndex();
			Author a1 = new Author();
			String[] str=author[i].split(",");
			a.setAuthorOrder(i+1);
			a.setFirstName(str[0]);
			a.setMiddleName(str[1]);
			a.setLastName(str[2]);
			a.setEmail(str[3]);

			a.setIndexCode("J");
			a.setIndexNo((String)params.get("indexNo"));
			authors.add(a);
		}
		if(type.equals(2)){
			JournalPaperChinese journalPaperChinese =new JournalPaperChinese();
			journalPaperChinese.setIndexNo((String)params.get("indexNo"));
			journalPaperChinese.setTitle2((String)params.get("title2"));
			journalPaperChinese.setTitle1((String)params.get("title1"));
			journalPaperChinese.setJournalIndexNo((String)params.get("journalIndexNo"));
			journalPaperChinese.setYear(Integer.parseInt((String)params.get("year")) );
			journalPaperChinese.setVolume((String)params.get("volume"));
			journalPaperChinese.setNum((String)params.get("num"));
			journalPaperChinese.setStartPage((String)params.get("startPage"));
			journalPaperChinese.setEndPage((String)params.get("endPage"));
			journalPaperChinese.setDiskPath((String)params.get("diskPath"));
			journalPaperChinese.setPosition((String)params.get("position"));
			journalPaperChinese.setFirstKeyword((String)params.get("firstKeyword"));
			journalPaperChinese.setSecondKeyword((String)params.get("secondKeyword"));
			journalPaperChinese.setThirdKeyword((String)params.get("thirdKeyword"));
			journalPaperChinese.setForthKeyword((String)params.get("forthKeyword"));
			journalPaperChinese.setNote((String)params.get("note"));
			System.out.println(journalPaperChinese);
			String item = (String)params.get("item");
			System.out.println(item);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date());
			Boolean bo = journalService.addJournalPaper(type, journalPaperChinese, item,date);
			str1= item +"+"+date+"+"+1;
		}else{
			JournalPaperEnglish journalPaperEnglish =new JournalPaperEnglish();
			journalPaperEnglish.setIndexNo((String)params.get("indexNo"));
			journalPaperEnglish.setTitle((String)params.get("title"));
			journalPaperEnglish.setJournalIndexNo((String)params.get("journalIndexNo"));
			journalPaperEnglish.setYear(Integer.parseInt((String)params.get("year")) );
			journalPaperEnglish.setVolume((String)params.get("volume"));
			journalPaperEnglish.setNum((String)params.get("num"));
			journalPaperEnglish.setStartPage((String)params.get("startPage"));
			journalPaperEnglish.setEndPage((String)params.get("endPage"));
			journalPaperEnglish.setDiskPath((String)params.get("diskPath"));
			journalPaperEnglish.setPosition((String)params.get("position"));
			journalPaperEnglish.setFirstKeyword((String)params.get("firstKeyword"));
			journalPaperEnglish.setSecondKeyword((String)params.get("secondKeyword"));
			journalPaperEnglish.setThirdKeyword((String)params.get("thirdKeyword"));
			journalPaperEnglish.setForthKeyword((String)params.get("forthKeyword"));
			journalPaperEnglish.setNote((String)params.get("note"));
			System.out.println(journalPaperEnglish);
			String item = (String)params.get("item");
			System.out.println(item);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date());
			Boolean bo = journalService.addJournalPaper(type,journalPaperEnglish, item,date);
			str1= item +"+"+date+"+"+1;

		}
		authorIndexService.addAuthorIndexs(authors);

		Gson gson = new Gson();

		return gson.toJson(str1);
	}
	
	
	/*@RequestMapping(value = "/generateItemChinese", method = RequestMethod.POST)
	public String generateItemChinese(HttpServletRequest request) {
		List<Author> authors = new ArrayList<Author>();
		String title = request.getParameter("title");
		String journalName = request.getParameter("journalName");
		String volume = request.getParameter("volume");
		String num = request.getParameter("num");
		String year = request.getParameter("year");
		String startPage = request.getParameter("startPage");
		String endPage = request.getParameter("endPage");
		String authorInfo=request.getParameter("tableInfo");
		String[] author=authorInfo.split(";");
		for (int i = 0; i < author.length; i++) {
			Author a=new Author();
			String []str=author[i].split(",");
			a.setAuthorFullName(str[0]);
			if(str.length>1){
				a.setEmail(str[1]);
			}
			authors.add(a);
		}
		String Item = "";

		for (int i = 0; i < authors.size() - 1; i++) {
			Item += authors.get(i).getAuthorFullName() + ",";
		}
		Item += authors.get(authors.size() - 1).getAuthorFullName() + ".";
		Item += title + "[J]" + ".";
		Item += journalName + "," + volume + "(" + num + ")" + "," + year + ".";
		Item += startPage + "-" + endPage;
		Gson gson = new Gson();
		return gson.toJson(Item);
	}*/

	@RequestMapping(value = "/generateItem", method = RequestMethod.POST)
	public String generateItemEnglish(HttpServletRequest request) {
		List<Author> authors = new ArrayList<Author>();
		String type = request.getParameter("type");
		String title = request.getParameter("title");
		String journalName = request.getParameter("journalName");
		String volume = request.getParameter("volume");
		String num = request.getParameter("num");
		String year = request.getParameter("year");
		String startPage = request.getParameter("startPage");
		String endPage = request.getParameter("endPage");
		String authorInfo=request.getParameter("tableInfo");
		String[] author=authorInfo.split(";");
		for (int i = 0; i < author.length; i++) {
			Author a=new Author();
			String []str=author[i].split(",");
			a.setAuthorFullName(str[0]);
			if(type.equals("1")){
				if(a.getAuthorFullName().split(" ").length>2){
					a.setFirstName(a.getAuthorFullName().split(" ")[0]);
					a.setMiddleName(a.getAuthorFullName().split(" ")[1]);
					a.setLastName(a.getAuthorFullName().split(" ")[2]);
				}else{
					a.setFirstName(a.getAuthorFullName().split(" ")[0]);
					a.setMiddleName("");
					a.setLastName(a.getAuthorFullName().split(" ")[1]);
				}

			}else {
				a.setFirstName(str[0]);
			}

			if(str.length>1){
				a.setEmail(str[1]);
			}
			authors.add(a);
		}
		String item = "";
		if(type.equals("1")){//英文期刊文献
			String lastName;
			String middleName;
			String firstNameName;
			for (int i = 0; i < authors.size() - 1; i++) {
				Author a = authors.get(i);
				lastName = a.getFirstName();
				middleName = a.getMiddleName();
				firstNameName =a.getLastName() ;

				// 中间名不存在
				if (middleName.equals("")) {
					item += toUpperCaseFirstLetter(lastName) + ", "
							+ getFirstLetter(firstNameName) + "., ";
				} else {
					item += toUpperCaseFirstLetter(lastName) + ", "
							+ getFirstLetter(middleName) + ". "
							+ getFirstLetter(firstNameName) + "., ";
				}
			}

			// 最后以为作者
			lastName = authors.get(authors.size() - 1).getLastName();
			middleName = authors.get(authors.size() - 1).getMiddleName();
			firstNameName = authors.get(authors.size() - 1).getFirstName();

			// 中间名不存在
			if (middleName.equals("")) {
				item += toUpperCaseFirstLetter(lastName) + ", "
						+getFirstLetter(firstNameName) + ".. ";
			} else {
				item += toUpperCaseFirstLetter(lastName) + ", "
						+ getFirstLetter(middleName) + ". "
						+ getFirstLetter(firstNameName) + ".. ";
			}

			item += year + ". ";
			item += title + "[JE]. ";
			item += journalName + " " + volume + "(" + num + ")" + ":" + startPage
					+ "-" + endPage + ". ";
		}else{
			for (int i = 0; i < authors.size() - 1; i++) {
				item += authors.get(i).getAuthorFullName() + ",";
			}
			item += authors.get(authors.size() - 1).getAuthorFullName() + ".";
			item += title + "[JC]" + ".";
			item += journalName + "," + volume + "(" + num + ")" + "," + year + ".";
			item += startPage + "-" + endPage;
		}
		Gson gson = new Gson();
		return gson.toJson(item);
	}

	@RequestMapping(value = "/deleteJournalPaper", method = RequestMethod.POST)
	public String deleteJournalPaper( @RequestBody Map<String, Object> params) {
		String type = (String) params.get("type");
		String indexNo=(String) params.get("indexNo");
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user=(User) session.getAttribute("userInfo");
		boolean bo = journalService.deleteJournalPaper(type,indexNo,user);
		Gson gson = new Gson();
		return gson.toJson(bo);
	}

	@RequestMapping(value = "/editJournalPaper", method = RequestMethod.POST)
	public String editJournalPaper( @RequestBody Map<String, Object> params) {
		String type = (String) params.get("type");
		String str="";
		if(type.equals("2")){
			JournalPaperChinese journalPaperChinese =new JournalPaperChinese();
			journalPaperChinese.setIndexNo((String)params.get("indexNo"));
			journalPaperChinese.setTitle2((String)params.get("title2"));
			journalPaperChinese.setTitle1((String)params.get("title1"));
			journalPaperChinese.setJournalIndexNo((String)params.get("journalIndexNo"));
			journalPaperChinese.setYear(Integer.parseInt((String)params.get("year")) );
			journalPaperChinese.setVolume((String)params.get("volume"));
			journalPaperChinese.setNum((String)params.get("num"));
			journalPaperChinese.setStartPage((String)params.get("startPage"));
			journalPaperChinese.setEndPage((String)params.get("endPage"));
			journalPaperChinese.setDiskPath((String)params.get("diskPath"));
			journalPaperChinese.setPosition((String)params.get("position"));
			journalPaperChinese.setFirstKeyword((String)params.get("firstKeyword"));
			journalPaperChinese.setSecondKeyword((String)params.get("secondKeyword"));
			journalPaperChinese.setThirdKeyword((String)params.get("thirdKeyword"));
			journalPaperChinese.setForthKeyword((String)params.get("forthKeyword"));
			journalPaperChinese.setNote((String)params.get("note"));
			System.out.println(journalPaperChinese);
			String item = (String)params.get("item");
			System.out.println(item);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date());
			boolean bo = journalService.editJournalPaper(type,journalPaperChinese, item,date);
			str= date;
		}else{
			JournalPaperEnglish journalPaperEnglish =new JournalPaperEnglish();
			journalPaperEnglish.setIndexNo((String)params.get("indexNo"));
			journalPaperEnglish.setTitle((String)params.get("title"));
			journalPaperEnglish.setJournalIndexNo((String)params.get("journalIndexNo"));
			journalPaperEnglish.setYear(Integer.parseInt((String)params.get("year")) );
			journalPaperEnglish.setVolume((String)params.get("volume"));
			journalPaperEnglish.setNum((String)params.get("num"));
			journalPaperEnglish.setStartPage((String)params.get("startPage"));
			journalPaperEnglish.setEndPage((String)params.get("endPage"));
			journalPaperEnglish.setDiskPath((String)params.get("diskPath"));
			journalPaperEnglish.setPosition((String)params.get("position"));
			journalPaperEnglish.setFirstKeyword((String)params.get("firstKeyword"));
			journalPaperEnglish.setSecondKeyword((String)params.get("secondKeyword"));
			journalPaperEnglish.setThirdKeyword((String)params.get("thirdKeyword"));
			journalPaperEnglish.setForthKeyword((String)params.get("forthKeyword"));
			journalPaperEnglish.setNote((String)params.get("note"));
			System.out.println(journalPaperEnglish);
			String item = (String)params.get("item");
			System.out.println(item);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date());
			boolean bo = journalService.editJournalPaper(type,journalPaperEnglish, item,date);
			str= date;
		}

		Gson gson = new Gson();
		return gson.toJson(str);
	}
	 /**
     * 将一个字符串的首字母大写
     * 2011-10-08
     * 
     * @author Lei Xia
     */
    public String toUpperCaseFirstLetter(String str) {
        String firstLetter = "";
        String latterString = "";
        if (!str.equals("")) {
            firstLetter = str.substring(0, 1);
            latterString = str.substring(1, str.length());
            firstLetter = firstLetter.toUpperCase();
        }

        return (firstLetter + latterString);
    }
    
    /**
     * 得到一个字符串的大写首字母
     * 2011-10-08
     * 
     * @author Lei Xia
     */
    public String getFirstLetter(String str) {
        String firstLetter = "";
        if (!str.equals("")) {
            firstLetter = str.substring(0, 1);
            firstLetter = firstLetter.toUpperCase();
        }

        return firstLetter;
    }

}
